package us.gaaoc.framework.dao;

import java.util.List;

import org.hibernate.Query;

import us.gaaoc.framework.model.DocumentBinaries;
import us.gaaoc.framework.model.Documents;

@SuppressWarnings("unchecked")
public class DocumentBinariesDAOHibernate 
	extends GenericHibernateDAO<DocumentBinaries, String, DocumentBinariesDAO>
	implements DocumentBinariesDAO {

	/*
	 * (non-Javadoc)
	 * @see us.gaaoc.framework.dao.DocumentBinariesDAO#insertDocumentBinary(java.lang.String, java.lang.String, int, java.lang.String)
	 */
	public void insertDocumentBinary(String uuid, Documents metaDoc, 
			int version, String path) {
		
		DocumentBinaries binaryEntry = new DocumentBinaries();
		binaryEntry.setUuid(uuid);
		binaryEntry.setMetaDataUuid(metaDoc);
		binaryEntry.setVersion(version);
		binaryEntry.setPath(path);
		
		this.makePersistent(binaryEntry);
	}

	/*
	 * (non-Javadoc)
	 * @see us.gaaoc.framework.dao.DocumentBinariesDAO#getCurrentVersion(java.lang.String)
	 */
	public int getCurrentVersion(String metaDataUuid) {
		
		int version = 0;
		
		Query selectStatement = this.getSession().createQuery(
				"select count(*) from DocumentBinaries " +
				"where metaDataUuid = ?");
		selectStatement.setString(0, metaDataUuid);
		
		version = Integer.parseInt(Long.toString((Long)selectStatement
				.uniqueResult()));
		
		return version;
	}

	/*
	 * (non-Javadoc)
	 * @see us.gaaoc.framework.dao.DocumentBinariesDAO#findAllDocumentBinaries(int)
	 */
	public List<DocumentBinaries> findAllDocumentBinaries(int rowNumber) {
		
		String getAllDocumentBinariesQuery = "from DocumentBinaries d";
		List<DocumentBinaries> allDocumentBinaries;
		
		Query databaseResult = this.getSession().createQuery(getAllDocumentBinariesQuery)
			.setFirstResult(rowNumber).setMaxResults(1000);
		
		allDocumentBinaries = databaseResult.list();
		
		return allDocumentBinaries;
	}

	/*
	 * (non-Javadoc)
	 * @see us.gaaoc.framework.dao.DocumentBinariesDAO#updateDocumentBinaryPath(java.lang.String)
	 */
	public void updateDocumentBinaryPath(String uuid, String path) {
		
		DocumentBinaries binaryEntry = this.findDocumentBinaryByUuid(uuid);
		binaryEntry.setPath(path);
		this.makePersistent(binaryEntry);
	}

	/*
	 * (non-Javadoc)
	 * @see us.gaaoc.framework.dao.DocumentBinariesDAO#findDocumentBinaryByUuid(java.lang.String)
	 */
	public DocumentBinaries findDocumentBinaryByUuid(String uuid) {
		
		DocumentBinaries entry;
		
		String getDocumentBinariesEntry = "from DocumentBinaries d " +
			"where metaDataUuid = ? " +
			"order by version desc";
		Query databaseResult = this.getSession().createQuery(getDocumentBinariesEntry);
		databaseResult.setString(0, uuid);
		
		List<DocumentBinaries> resultList = databaseResult.list();
		entry = resultList.get(0);
		
		return entry;
	}
}